package com.simple.simple_view.handler.security;

import com.simple.simple_view.domain.ResponseResult;
import com.simple.simple_view.domain.enums.AppHttpCodeEnum;
import com.simple.simple_view.utils.WebUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/*
 *@description: 异常处理
 *@author: hisen
 *@Time: 2023/10/29  1:05
 */
@Component
@Slf4j
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) {
        log.error(e.getMessage(), e);
        ResponseResult result;
        if(e instanceof InternalAuthenticationServiceException ||e instanceof BadCredentialsException)result=ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_ERROR);
        else if(e instanceof InsufficientAuthenticationException)result=ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        else result=ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR);

        WebUtil.renderString(httpServletResponse, result);
    }
}
